package com.senjoeson.teamfriends.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.bean.FriendMessage;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.MyToast;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadFileListener;

public class SendMessageActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener, View.OnClickListener {

    @BindView(R.id.sendMessage)
    ImageView mSendMessage;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.content)
    EditText mContent;
    @BindView(R.id.movie)
    CheckBox mMovie;
    @BindView(R.id.food)
    CheckBox mFood;
    @BindView(R.id.trip)
    CheckBox mTrip;
    @BindView(R.id.study)
    CheckBox mStudy;
    @BindView(R.id.goout)
    CheckBox mGoout;
    @BindView(R.id.games)
    CheckBox mGames;
    @BindView(R.id.curious)
    CheckBox mCurious;
    @BindView(R.id.location)
    TextView mLocation;
    @BindView(R.id.send)
    Button mSend;
    @BindView(R.id.addpicture)
    ImageView mAddPicture;
    List<CheckBox> mCheckBoxes = new ArrayList<>();
    private static final int IMAGE_REQUEST_CODE = 102;
    public String portraitPath;
    //声明AMapLocationClient类对象
    public LocationClient mLocationClient = null;
    public String mLocationCity;
    public LatLng mLatLng;

    private MyLocationListener mMyLocationListener = new MyLocationListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_message);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(mMyLocationListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        option.setIgnoreKillProcess(false);
        option.SetIgnoreCacheException(false);
        option.setEnableSimulateGps(false);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
        initHashMap();
        initListener();
        initChecksState();
    }

    private void initListener() {
        mMovie.setOnCheckedChangeListener(this);
        mFood.setOnCheckedChangeListener(this);
        mTrip.setOnCheckedChangeListener(this);
        mStudy.setOnCheckedChangeListener(this);
        mGoout.setOnCheckedChangeListener(this);
        mGames.setOnCheckedChangeListener(this);
        mCurious.setOnCheckedChangeListener(this);
        mSend.setOnClickListener(this);
        mSendMessage.setOnClickListener(this);
        mAddPicture.setOnClickListener(this);
        mLocation.setOnClickListener(this);
    }

    private void initHashMap() {
        mCheckBoxes.add(mMovie);
        mCheckBoxes.add(mFood);
        mCheckBoxes.add(mTrip);
        mCheckBoxes.add(mStudy);
        mCheckBoxes.add(mGoout);
        mCheckBoxes.add(mGames);
        mCheckBoxes.add(mCurious);
    }

    /**
     * 初始化checkbox的状态
     */
    public void initChecksState() {
        for (CheckBox checkBox : mCheckBoxes) {
            checkBox.setChecked(false);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        initChecksState();
        buttonView.setChecked(isChecked);
    }

    @Override
    public void onClick(View v) {
        //发送搭伙
        //主要逻辑 获取用户id  然后添加到搭伙信息中
        switch (v.getId()) {
            case R.id.send:
                uploadFriendMessage();
                break;
            case R.id.sendMessage:
                uploadFriendMessage();
                break;
            case R.id.addpicture:
                pickPortrait();
                break;
            case R.id.location:
                mLocationClient.start();
                break;
        }
    }

    /**
     * 添加一个搭伙信息
     */
    private void uploadFriendMessage() {
        String content = mContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            MyToast.showToast("还没有填写内容哦！");
            return;
        }
        if (TextUtils.isEmpty(portraitPath)) {
            MyToast.showToast("请添加一张图片");
            return;
        }
        String hobbiesName = null;
        for (CheckBox checkBox : mCheckBoxes) {
            if (checkBox.isChecked()) {
                hobbiesName = checkBox.getText().toString().trim();
            }
        }
        if (TextUtils.isEmpty(hobbiesName)) {
            MyToast.showToast("请选择一个兴趣哦");
            return;
        }
        User currentUser = BmobUser.getCurrentUser(User.class);
        final FriendMessage friendMessage = new FriendMessage();
        friendMessage.setUser_id(currentUser.getObjectId());
        friendMessage.setAuthor_name(currentUser.getNickname());
        friendMessage.setComment_num(0);
        friendMessage.setLike_num(0);
        friendMessage.setCityname(mLocationCity);
        friendMessage.setAddress(mLocation.getText().toString());
        friendMessage.setAddress_latlan(mLatLng);
        friendMessage.setUser_icon(currentUser.getPortrait().getFileUrl());
        friendMessage.setHobby_name(hobbiesName);
        friendMessage.setContent(content);
        friendMessage.setTime(System.currentTimeMillis());
        friendMessage.setHelpType(false);   //默认不是救援的
        final BmobFile bmobFile = new BmobFile(new File(portraitPath));
        bmobFile.upload(new UploadFileListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    friendMessage.setPicture(bmobFile);
                    friendMessage.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                MyToast.showToast("保存成功");

                                finish();
                            } else {
                                MyToast.showToast(e.toString());
                            }
                        }
                    });
                } else {
                    MyToast.showToast(e.toString());
                }
            }
        });


    }


    /**
     * 从相册中获取头像
     */
    private void pickPortrait() {
        Matisse.from(SendMessageActivity.this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(IMAGE_REQUEST_CODE);
        /*Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);*/

    }

    List<Uri> mSelected;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
            mSelected = Matisse.obtainResult(data);
            Uri uri = mSelected.get(0);
            mAddPicture.setImageURI(uri);
            portraitPath = getPath(uri);
            ALog.d("mSelected: " + portraitPath);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 通过uri获取图片路径
     *
     * @param uri
     * @return
     */
    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient = null;

        }
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                mLatLng = new LatLng(latitude, longitude);
                Address mAddress = location.getAddress();

                mLocation.setText(mAddress.address);
                ALog.d(mAddress.address);
                mLocationCity = location.getCity();
                mLocationClient.stop();
            } else {
                ALog.d("定位失败");
            }

        }
    }
}
